import BaseController from "./base";
import BookModel from "../models/book";
import { Application, Request, Response, NextFunction } from "express";
import { Book } from "../entities/Book";

export default class BookController extends BaseController {
  model!: BookModel;

  constructor(app: Application) {
    super(new BookModel(app));
  }

  async create(req: Request, res: Response, next: NextFunction) {
    const data = req.body as unknown as { title: string; author: string };
    const result = await this.model.insert(data);
    console.log("🚀 ~ BookController ~ create ~ result:", result);
    res.end(result);
  }

  async update(req: Request, res: Response, next: NextFunction) {
    const data = req.body as unknown as Book;
    const newBook = await this.model.update(data);
    console.log("🚀 ~ BookController ~ update ~ newBook:", newBook);
    res.json(newBook);
  }

  async search(req: Request, res: Response, next: NextFunction) {
    let { title } = req.query;
    if (title === undefined) {
      return res.end("not found <titile> param");
    } else {
      title = Array.isArray(title) ? title.join(",") : title;
      const matcheds = await this.model.find(title as string);
      res.json(matcheds);
    }
  }

  async remove(req: Request, res: Response, next: NextFunction) {
    const { id } = req.query;
    const result = await this.model.del(id as unknown as number);
    console.log("🚀 ~ BookController ~ remove ~ result:", result);

    res.json({ success: true, result });
  }
}
